"use strict"

var Router = require('koa-router');
var config = require('../../../config/config.js');
var Category = require('../../../model/category.js');
var CategoryDao = require('../../../dao/category.js');
var debug = require('debug')('category');

console.log('router:' + config.baseUrl + '/v1/category');
var router = new Router({
    prefix: config.baseUrl + '/v1/category'
});
/**
{
    "name": "护理",
    "subCategories":["皮肤护理","眼部护理"] //没有可以空着
}
*/
router.post('/', function*() {
    // console.log(this.request.body);
    // this.request.body 应该是 中间件koa-body-parser添加的
    var inParams = JSON.parse(this.request.body);
    var cateList = [];
    if (Object.prototype.toString.call(inParams) === '[object Array]') {
        inParams.forEach(function(item) {
            var aCategory = new Category({
                name: item.name,
                subcategories: item.subcategories || []
            });
            cateList.push(aCategory);
        });
    } else {
        var aCategory = new Category({
            name: inParams.name,
            subcategories: inParams.subcategories || []
        });
        cateList.push(aCategory);
    }
    // debug(cateList);

    try {
        var result = yield CategoryDao.save(cateList);
        this.body = JSON.stringify(result);
    } catch (e) {
        this.body = 'save category error ' + e.toString();
    }
});

router.get('/list', function*() {
    // var category = yield Category.find({}).exec();
    var category = yield CategoryDao.findAll();
    // console.log(category);
    this.body = category;
});

router.get('/:cateName', function*() {
    var category = yield CategoryDao.findByName(this.params.cateName);
    this.body = category;
});

router.get('/:id', function*() {
    // var category = yield Category.findOne({
    //  _id: this.params.id
    // }).exec();
    console.log(this.params.id);
    var category = yield CategoryDao.findById(this.params.id);
    this.body = category;
});

module.exports = router;